package com.yingpai.fitness.dvp_2_0.main.fragment.fitness;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.DieCollocationDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.DietCollocationActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.food.HomeFoodFragmentDataBean;
import com.yingpai.fitness.entity.food.HomeFoodMoreBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 饮食fragment
 */
public class FitnessDieteticFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    private Unbinder unbinder;
    private TokenBean token;
    @BindView(R.id.home_food_banner)
    Banner banner;
    private List<String> bannerList = new ArrayList<>();
    @BindView(R.id.home_food_parent_rv_list)
    XListView home_food_parent_rv_list;
    @BindView(R.id.gridview)
    XGridView xGridView;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedScrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    @BindView(R.id.empty)
    LinearLayout empty;
    private QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietDetailListBean> quickAdapter;
    private QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietTimeCategoryListBean> gQuickadapter;
    private int pageNum = 1;
    private int pageSize = 4;

    public static FitnessDieteticFragment getInstance() {
        return new FitnessDieteticFragment();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_dietetic, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        token = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        //让scrollview位置顶上去
        nestedScrollView.smoothScrollTo(0, 0);
        home_food_parent_rv_list.setFocusable(false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //设置广告指示器的位置
        banner.setIndicatorGravity(BannerConfig.CENTER);
        quickAdapter = new QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietDetailListBean>(getActivity(),
                R.layout.home_food_list_child_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, HomeFoodFragmentDataBean.MapBean.DietDetailListBean item) {
                helper.setText(R.id.home_food_item_tv, item.getDetailList().get(0).getDietName());

                XGridView xGridView = helper.getView(R.id.gridview);
                final QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean> quickAdapter_child =
                        new QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean>(context, R.layout.home_food_list_child_item2, item.getDetailList()) {
                            @Override
                            protected void convert(BaseAdapterHelper helper_child, HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean item) {
                                helper_child.setText(R.id.home_food_child_name, item.getDietDetailName());
                                helper_child.setText(R.id.home_food_child_kca, item.getEnergy());
                                ImageView imageView = helper_child.getView(R.id.home_food_child_iv);
                                Glide.with(context)
                                        .load(item.getPhotoUrl())
                                        .centerCrop()
                                        .into(imageView);
                            }
                        };

                int size = item.getDetailList().size();
                setGridViewParam(xGridView, size);

                xGridView.setAdapter(quickAdapter_child);

                xGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", quickAdapter_child.getItem(position).getId());
                        startActivity(DieCollocationDetailActivity.class, bundle);
                    }
                });
            }
        };
        home_food_parent_rv_list.setAdapter(quickAdapter);

        gQuickadapter = new QuickAdapter<HomeFoodFragmentDataBean.MapBean.DietTimeCategoryListBean>(getActivity(), R.layout.item_food_diet_category_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, HomeFoodFragmentDataBean.MapBean.DietTimeCategoryListBean item) {
//                helper.setText(R.id.text,item.getDietCategoryName());
                ImageView imageView = helper.getView(R.id.image);
                Glide.with(context)
                        .load(item.getPhotoUrl())
                        .centerCrop()
                        .into(imageView);
            }
        };
        xGridView.setAdapter(gQuickadapter);

        xGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", gQuickadapter.getItem(position).getId());
                bundle.putString("title", gQuickadapter.getItem(position).getDietCategoryName());
                startActivity(DietCollocationActivity.class, bundle);

            }
        });
    }

    @Override
    protected void initData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", token.getId());
        httpParams.put("tagId", Constant.NUM_4);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.FITNESS_FRAGMENT_DATA, httpParams, Url.FITNESS_FRAGMENT_DATA,
                new Callback<HomeFoodFragmentDataBean>() {
                    @Override
                    public void onSuccess(HomeFoodFragmentDataBean bean) {
                        empty.setVisibility(View.GONE);
                        refreshLayout.finishRefresh();
                        refreshLayout.setNoMoreData(false);
                        if (bean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                            List<HomeFoodFragmentDataBean.MapBean.RecommendedDetailListBean> upList =
                                    bean.getMap().getRecommendedDetailList();//bannerAll Data

                            bannerList.clear();
                            for (int i = 0; i < upList.size(); i++) {
                                bannerList.add(upList.get(i).getPhotoUrl());
                            }

                            banner.setImages(bannerList)
                                    .setImageLoader(new GlideImageLoader())
                                    .start();

                            quickAdapter.clear();
                            quickAdapter.addAll(bean.getMap().getDietDetailList());

                            setGridViewParam(xGridView, bean.getMap().getDietTimeCategoryList().size());
                            gQuickadapter.clear();
                            gQuickadapter.addAll(bean.getMap().getDietTimeCategoryList());
                        } else {
                            empty.setVisibility(View.VISIBLE);
                            showToast(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        empty.setVisibility(View.VISIBLE);
                    }
                });
    }

    /**
     * 设置gridview参数
     *
     * @param gridView
     */
    private void setGridViewParam(GridView gridView, int size) {
        int length = 119;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;//密度
        //+4是为了加上4个水平间距，得到宽度
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        gridView.setColumnWidth(itemWidth); // 设置列表项宽
        gridView.setHorizontalSpacing(4); // 设置列表项水平间距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(size); // 设置列数量=列表集合数
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 2;
        initData();
    }

    @Override
    @OnClick({R.id.empty})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getMoreData();
    }

    private void getMoreData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.FITNESS_FOOD_MORE, httpParams, Url.FITNESS_FOOD_MORE,
                new Callback<HomeFoodMoreBean>() {
                    @Override
                    public void onSuccess(HomeFoodMoreBean bean) {
                        refreshLayout.finishLoadMore();
                        if (bean.getMap() == null || bean.getMap().getDietAndDetailList() == null || bean.getMap().getDietAndDetailList().size() == 0) {
                            refreshLayout.setNoMoreData(true);
                            refreshLayout.finishLoadMoreWithNoMoreData();
                        }
                        if (Constant.REQUEST_SUCCESS.equals(bean.getResult())) {
                            List<HomeFoodFragmentDataBean.MapBean.DietDetailListBean> list = new ArrayList<>();
                            for (int i = 0; i < bean.getMap().getDietAndDetailList().size(); i++) {
                                List<HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean> list1 = new ArrayList<>();
                                HomeFoodFragmentDataBean.MapBean.DietDetailListBean dietDetailListBean = new HomeFoodFragmentDataBean.MapBean.DietDetailListBean();
                                if (bean.getMap().getDietAndDetailList().get(i).getRandomDetailList() != null && bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().size() != 0) {
                                    for (int j = 0; j < bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().size(); j++) {
                                        HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean detailListBean = new HomeFoodFragmentDataBean.MapBean.DietDetailListBean.DetailListBean();
                                        detailListBean.setId(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getId());
                                        detailListBean.setCommonPrice(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getCommonPrice());
                                        detailListBean.setContent(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getContent());
                                        detailListBean.setCreateTime(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getCreateTime());
                                        detailListBean.setDicDietCategoryId(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getDicDietCategoryId());
                                        detailListBean.setDicDietCategoryName(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getDicDietCategoryName());
                                        detailListBean.setDietDetailName(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getDietDetailName());
                                        detailListBean.setDietId(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getDietId());
                                        detailListBean.setDietName(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getDietName());
                                        detailListBean.setEnergy(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getEnergy());
                                        detailListBean.setIsAbandoned(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).isIsAbandoned());
                                        detailListBean.setIsRecommended(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).isIsRecommended());
                                        detailListBean.setMemberPrice(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getMemberPrice());
                                        detailListBean.setPhotoUrl(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getPhotoUrl());
                                        detailListBean.setProperties(bean.getMap().getDietAndDetailList().get(i).getRandomDetailList().get(j).getProperties());
                                        list1.add(detailListBean);
                                        dietDetailListBean.setDetailList(list1);
                                    }
                                    list.add(dietDetailListBean);
                                }
                            }
                            quickAdapter.addAll(list);
                            quickAdapter.notifyDataSetChanged();
                        } else {
                            showToast(bean.getMsg());
                        }

                    }
                });
    }
}